package com.zengqingfa.examples.mybatisplus.interceptor;

import com.alibaba.fastjson.JSON;
import com.zengqingfa.examples.mybatisplus.context.UserInfoContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @fileName: AuthInterceptor
 * @author: zengqf3
 * @date: 2020-8-14 17:43
 * @description: 拦截器，可以获取到用户信息
 */
@Component
@Slf4j
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userCode = request.getHeader(UserInfoContext.KEY_USERINFO_IN_HTTP_HEADER);
        if(StringUtils.isBlank(userCode)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println("用户编码不能为空");
            writer.flush();
            writer.close();
            return false;
        }
        UserInfoContext.setUser(userCode);
        return super.preHandle(request, response, handler);
    }

    /**
     * 返回处理清除用户信息
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserInfoContext.clear();
    }
}
